package com.xuanyang.dormrepair.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xuanyang.dormrepair.config.ServiceException;
import com.xuanyang.dormrepair.model.entity.FloorRoom;
import com.xuanyang.dormrepair.model.enums.FloorRoomStatus;
import com.xuanyang.dormrepair.model.mapper.FloorRoomMapper;
import com.xuanyang.dormrepair.utils.JwtKit;
import com.xuanyang.dormrepair.utils.PageKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @AUTHOR soft
 * @DATE 2019/5/19 10:50
 * @DESCRIBE 楼层房间业务
 */
@Service
public class FloorRoomService {

    @Autowired
    private FloorRoomMapper roomMapper;

    /**
     * 登录成功则返回当前登录的楼层信息 失败null
     * @param floorRoom 楼层信息
     */
    @Transactional
    public FloorRoom login(FloorRoom floorRoom) {
        LambdaQueryWrapper<FloorRoom> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(FloorRoom::getHouseNo, floorRoom.getHouseNo())
                .eq(FloorRoom::getRoomNo, floorRoom.getRoomNo());

        FloorRoom one = roomMapper.selectOne(wrapper);
        if (one == null) throw new ServiceException("不存在的楼层！");

        if (one.getStatus().equals(FloorRoomStatus.DISABLED))
            throw new ServiceException("已被禁住，无法登录！");

        String md5 = JwtKit.md5(floorRoom.getUsername(), floorRoom.getPassword());
        if (md5.equals(one.getPassword())) {
            this.update(new FloorRoom().setId(one.getId()).setLoginTime(new Date()));

            return one;
        }
        return null;
    }

    @Transactional
    public boolean register(FloorRoom floorRoom) {
        if (exist(floorRoom)) throw new ServiceException("房间已存在无法添加！");
        floorRoom.setStatus(FloorRoomStatus.HASPEOPLE)
                .setPassword(JwtKit.md5(floorRoom.getUsername(), floorRoom.getPassword()));

        return roomMapper.insert(floorRoom) > 0;
    }

    @Transactional
    public boolean delete(Serializable pk) {
        FloorRoom room = byId(pk);
        if (room != null &&
                (StringUtils.isNotEmpty(room.getName()) || room.getLoginTime() != null)) {
            throw new ServiceException("该房间已住人，无法删除！");
        }
        return roomMapper.deleteById(pk) > 0;
    }

    @Transactional
    public boolean update(FloorRoom floorRoom) {
        Integer id = floorRoom.getId();
        FloorRoom room = byId(id);
        if (!room.getHouseNo().equals(floorRoom.getHouseNo()) ||
                !room.getRoomNo().equals(floorRoom.getRoomNo())) {
            if (exist(floorRoom)) throw new ServiceException("房间已存在无法修改！");
        }

        if (StringUtils.isNotEmpty(floorRoom.getPassword())) {
            floorRoom.setPassword(JwtKit.md5(room.getUsername(), floorRoom.getPassword()));
        } // nc1gA/QBd4fCyGrAv/m3Eg==

        return roomMapper.updateById(floorRoom) > 0;
    }

    public FloorRoom byId(Serializable pk) {
        return roomMapper.selectById(pk);
    }

    /**
     * 根据楼号和房间号查询房间信息
     */
    public FloorRoom byNos(String[] nos) {
        if (nos != null && nos.length == 2) {
            LambdaQueryWrapper<FloorRoom> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(FloorRoom::getHouseNo, nos[0])
                    .eq(FloorRoom::getRoomNo, nos[1])
                    .ne(FloorRoom::getStatus, FloorRoomStatus.DISABLED);
            return roomMapper.selectOne(wrapper);
        }
        return null;
    }

    public IPage<FloorRoom> page(int page, int limit, FloorRoom query) {
        LambdaQueryWrapper<FloorRoom> wrapper = Wrappers.lambdaQuery(query);

        return roomMapper.selectPage(PageKit.of(page, limit), wrapper);
    }

    /**
     * 获取所有的楼层
     */
    public List<String> floors() {
        LambdaQueryWrapper<FloorRoom> wrapper = Wrappers.lambdaQuery();
        wrapper.groupBy(FloorRoom::getHouseNo);

        List<FloorRoom> list = roomMapper.selectList(wrapper);
        if (!list.isEmpty()) {
            return list.stream().map(FloorRoom::getHouseNo).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 判断房间是不是已存在
     * @param room 房间信息
     */
    private boolean exist(FloorRoom room) {
        LambdaQueryWrapper<FloorRoom> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(FloorRoom::getHouseNo, room.getHouseNo())
                .eq(FloorRoom::getRoomNo, room.getRoomNo());

        return roomMapper.selectCount(wrapper) > 0;
    }
}
